package com.doubao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.user.constant.UserConstant;
import com.doubao.user.dto.request.UserApiKeyRequest;
import com.doubao.user.entity.User;
import com.doubao.user.entity.UserApiKey;
import com.doubao.user.mapper.UserApiKeyMapper;
import com.doubao.user.mapper.UserMapper;
import com.doubao.user.service.UserApiKeyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户API密钥服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserApiKeyServiceImpl extends ServiceImpl<UserApiKeyMapper, UserApiKey> implements UserApiKeyService {

    private final UserApiKeyMapper userApiKeyMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addApiKey(Long userId, UserApiKeyRequest request) {
        if (userId == null || request == null || StringUtils.isBlank(request.getApiProvider())
                || StringUtils.isBlank(request.getApiKey())) {
            return Result.failed("参数错误");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 检查用户是否已有同提供商的API密钥
        LambdaQueryWrapper<UserApiKey> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserApiKey::getUserId, userId)
                .eq(UserApiKey::getApiProvider, request.getApiProvider());
        UserApiKey existingKey = userApiKeyMapper.selectOne(wrapper);
        if (existingKey != null) {
            return Result.failed("该用户已有相同提供商的API密钥");
        }

        try {
            UserApiKey apiKey = new UserApiKey();
            apiKey.setUserId(userId);
            apiKey.setApiProvider(request.getApiProvider());
            apiKey.setApiKey(request.getApiKey());
            apiKey.setIsActive(request.getIsActive() != null ? request.getIsActive() : 1);
            apiKey.setQuotaLimit(request.getQuotaLimit());
            apiKey.setQuotaUsed(0L);
            apiKey.setCreatedAt(LocalDateTime.now());
            apiKey.setUpdatedAt(LocalDateTime.now());

            userApiKeyMapper.insert(apiKey);
            return Result.success();
        } catch (Exception e) {
            log.error("添加API密钥失败", e);
            return Result.failed("添加API密钥失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateApiKey(Long keyId, UserApiKeyRequest request) {
        if (keyId == null || request == null) {
            return Result.failed("参数错误");
        }

        UserApiKey apiKey = userApiKeyMapper.selectById(keyId);
        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        try {
            boolean needUpdate = false;

            if (StringUtils.isNotBlank(request.getApiKey()) && !request.getApiKey().equals(apiKey.getApiKey())) {
                apiKey.setApiKey(request.getApiKey());
                needUpdate = true;
            }

            if (request.getIsActive() != null && !request.getIsActive().equals(apiKey.getIsActive())) {
                apiKey.setIsActive(request.getIsActive());
                needUpdate = true;
            }

            if (request.getQuotaLimit() != null && !request.getQuotaLimit().equals(apiKey.getQuotaLimit())) {
                apiKey.setQuotaLimit(request.getQuotaLimit());
                needUpdate = true;
            }

            if (needUpdate) {
                apiKey.setUpdatedAt(LocalDateTime.now());
                userApiKeyMapper.updateById(apiKey);
            }

            return Result.success();
        } catch (Exception e) {
            log.error("更新API密钥失败", e);
            return Result.failed("更新API密钥失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteApiKey(Long keyId) {
        if (keyId == null) {
            return Result.failed("API密钥ID不能为空");
        }

        try {
            userApiKeyMapper.deleteById(keyId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除API密钥失败", e);
            return Result.failed("删除API密钥失败");
        }
    }

    @Override
    public List<UserApiKey> getUserApiKeys(Long userId) {
        if (userId == null) {
            return List.of();
        }

        LambdaQueryWrapper<UserApiKey> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserApiKey::getUserId, userId)
                .orderByDesc(UserApiKey::getCreatedAt);

        return userApiKeyMapper.selectList(wrapper);
    }

    @Override
    public IPage<UserApiKey> getUserApiKeysPage(Long userId, int page, int size) {
        if (userId == null) {
            return new Page<>();
        }

        LambdaQueryWrapper<UserApiKey> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserApiKey::getUserId, userId)
                .orderByDesc(UserApiKey::getCreatedAt);

        Page<UserApiKey> pageQuery = new Page<>(page, size);
        return userApiKeyMapper.selectPage(pageQuery, wrapper);
    }

    @Override
    public UserApiKey getApiKeyById(Long keyId) {
        if (keyId == null) {
            return null;
        }
        return userApiKeyMapper.selectById(keyId);
    }

    @Override
    public UserApiKey getApiKeyByProvider(Long userId, String apiProvider) {
        if (userId == null || StringUtils.isBlank(apiProvider)) {
            return null;
        }

        LambdaQueryWrapper<UserApiKey> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserApiKey::getUserId, userId)
                .eq(UserApiKey::getApiProvider, apiProvider)
                .eq(UserApiKey::getIsActive, 1)
                .orderByDesc(UserApiKey::getCreatedAt);

        return userApiKeyMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateActiveStatus(Long keyId, Integer isActive) {
        if (keyId == null || isActive == null) {
            return Result.failed("参数错误");
        }

        try {
            userApiKeyMapper.updateActiveStatus(keyId, isActive);
            return Result.success();
        } catch (Exception e) {
            log.error("更新API密钥激活状态失败", e);
            return Result.failed("更新API密钥激活状态失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> increaseQuotaUsed(Long keyId, Long quota) {
        if (keyId == null || quota == null || quota <= 0) {
            return Result.failed("参数错误");
        }

        try {
            userApiKeyMapper.increaseQuotaUsed(keyId, quota);
            return Result.success();
        } catch (Exception e) {
            log.error("增加已用配额失败", e);
            return Result.failed("增加已用配额失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> resetQuotaUsed(Long keyId) {
        if (keyId == null) {
            return Result.failed("API密钥ID不能为空");
        }

        try {
            userApiKeyMapper.resetQuotaUsed(keyId);
            return Result.success();
        } catch (Exception e) {
            log.error("重置已用配额失败", e);
            return Result.failed("重置已用配额失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateQuotaLimit(Long keyId, Long quotaLimit) {
        if (keyId == null || quotaLimit == null) {
            return Result.failed("参数错误");
        }

        try {
            userApiKeyMapper.updateQuotaLimit(keyId, quotaLimit);
            return Result.success();
        } catch (Exception e) {
            log.error("更新配额限制失败", e);
            return Result.failed("更新配额限制失败");
        }
    }

    @Override
    public boolean isQuotaExceeded(Long keyId) {
        if (keyId == null) {
            return true;
        }

        UserApiKey apiKey = userApiKeyMapper.selectById(keyId);
        if (apiKey == null || apiKey.getIsActive() != 1) {
            return true;
        }

        // 如果没有设置限额，则视为不限额
        if (apiKey.getQuotaLimit() == null || apiKey.getQuotaLimit() <= 0) {
            return false;
        }

        return apiKey.getQuotaUsed() >= apiKey.getQuotaLimit();
    }

    @Override
    public Result<Boolean> validateApiKey(String apiProvider, String apiKey) {
        if (StringUtils.isBlank(apiProvider) || StringUtils.isBlank(apiKey)) {
            return Result.success(false);
        }

        // TODO: 实际调用相应的API提供商服务验证密钥是否有效
        // 这里仅做简单模拟，实际项目中应该调用相应的API服务验证

        boolean isValid = false;
        try {
            switch (apiProvider) {
                case UserConstant.API_PROVIDER_OPENAI:
                    // 调用OpenAI API验证
                    isValid = simulateOpenAIValidation(apiKey);
                    break;
                case UserConstant.API_PROVIDER_CLAUDE:
                    // 调用Claude API验证
                    isValid = simulateClaudeValidation(apiKey);
                    break;
                case UserConstant.API_PROVIDER_DEEPSEEK:
                    // 调用DeepSeek API验证
                    isValid = simulateDeepSeekValidation(apiKey);
                    break;
                default:
                    isValid = false;
            }

            return Result.success(isValid);
        } catch (Exception e) {
            log.error("验证API密钥失败", e);
            return Result.success(false);
        }
    }

    // 模拟OpenAI API验证
    private boolean simulateOpenAIValidation(String apiKey) {
        // 实际项目中应该调用OpenAI API验证
        return apiKey.startsWith("sk-") && apiKey.length() > 30;
    }

    // 模拟Claude API验证
    private boolean simulateClaudeValidation(String apiKey) {
        // 实际项目中应该调用Claude API验证
        return apiKey.startsWith("sk-ant-") && apiKey.length() > 30;
    }

    // 模拟DeepSeek API验证
    private boolean simulateDeepSeekValidation(String apiKey) {
        // 实际项目中应该调用DeepSeek API验证
        return apiKey.length() > 30;
    }
}